package com.dendi.controller;

import com.dendi.service.UserService;
import com.dendi.util.Sha1Util;
import com.dendi.util.WeiChatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

@Controller
public class WechatController2 {

    @Autowired
    UserService userService;
    private static String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=";

    @RequestMapping( "/getLocation2")
    public String getLocation(HttpServletRequest request,ModelMap model) throws Exception {
        System.out.println("url"+request.getRequestURI());
        System.out.println("url222222"+request.getServletPath());
        String param = request.getQueryString();
        System.out.println("url33333"+param);
        String url = request.getServletPath();//获取请求路径（不带参数）
        if(param!=null){
            url = url+"?"+param;//组合成完整请求URL
        }
        String projectnameP = request.getContextPath();
        String projectName = projectnameP.substring(projectnameP.lastIndexOf('/')+1,projectnameP.length());  //获取工程名,如testW
        if(!"".equals(projectName)){
            projectName ="/"+projectName;
        }
        String port = String.valueOf(request.getServerPort());//获取端口号
        if(!"80".equals(port)){//不是80端口时需加端口号
            port = ":"+port;
        }else{
            port = "";
        }
        String strBackUrl = "http://" + request.getServerName()+port+projectName+url;
        System.out.println("strBackUrl  "+strBackUrl);

//		String code=req.getParameter("code");
//		String openId= WeiChatUtil.getOpenId(code);
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        finalpackage.put("timestamp", timestamp);
        finalpackage.put("noncestr", nonce_str);
        String ticket = WeiChatUtil.getjsApiTicket(ticketUrl, WeiChatUtil.getAccessToken());
        finalpackage.put("jsapi_ticket", ticket);
        finalpackage.put("url", strBackUrl);

        String signature = Sha1Util.createSHA1Sign(finalpackage);
//		model.addAttribute("timestamp ",timestamp);
        System.out.println("timestamp "+timestamp);
        System.out.println("noncestr "+nonce_str);
        System.out.println("signature "+signature);
        System.out.println("jsapi_ticket "+ticket);

        model.addAttribute("timeStamp",timestamp);
        model.addAttribute("nonceStr",nonce_str);
        model.addAttribute("signature", signature);
//		model.addAttribute("signature ",signature);

        return "map2";
    }



}
